#include <iostream>
#include <mutex>
#include <condition_variable>
#include <deque>
#include <thread>
#include <semaphore>
std::mutex mutex;
std::mutex mutex2;
std::counting_semaphore<6> csem(0);
//std::binary_semaphore bsem(0);
int c = 0;
struct task {
    task(int value) : v(value) {}
    void operator=(const task& t) {
        this->v = t.v;
    }
    int v;
};
std::deque<task> cache;


void consumer()
{
    while (true) {
        //防止虚假唤醒
        while (cache.empty()) {
            csem.acquire();
        }
        task t(0);
        {
            std::lock_guard<std::mutex> lck(mutex2);
            if (cache.empty()) continue;
            t = cache.front();
            cache.pop_front();
            //处理
            std::cout << "线程: " << std::this_thread::get_id() << "正在处理任务" << t.v << std::endl;
        }
        

        std::this_thread::sleep_for(std::chrono::milliseconds(1));
    }

}
void producer()
{
    while (true) {
        {
            std::lock_guard<std::mutex> lck(mutex);
            cache.emplace_back(c++);
            cache.emplace_back(c++);
            cache.emplace_back(c++);
            cache.emplace_back(c++);
            
        }
        csem.release(1);
        csem.release(1);
        csem.release(1);
        csem.release(1);
        //

        std::this_thread::sleep_for(std::chrono::milliseconds(500));
    }

}

int main()
{
    std::thread t1(producer);
    std::thread t2(consumer);
    std::thread t3(consumer);

    t1.join();
    t2.join();
    t3.join();
    return 0;
}